package com.github.cyf.cacheManager;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * @author chenyifan
 * @create 2025-02-06 10:38
 */
@Component
@Slf4j
public class CacheManagerTrigger {

    private static ConcurrentHashMap<String, ScheduledFuture<?>> cacheFutureMap = new ConcurrentHashMap<>();

    private final ThreadPoolTaskScheduler threadPoolTaskScheduler;

    public CacheManagerTrigger(ThreadPoolTaskScheduler threadPoolTaskScheduler) {
        this.threadPoolTaskScheduler = threadPoolTaskScheduler;
    }

    /**
     * 添加定时刷新缓存的任务
     * @param cacheManager
     */
    public void addTask(CacheManager cacheManager) {
        CronTrigger cron = new CronTrigger(cacheManager.getCronExpression());
        ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(cacheManager::refreshCache, cron);
        cacheFutureMap.put(cacheManager.getCacheName().getName(), future);
        log.info("cache {} refresh task add success", cacheManager.getCacheName());
    }

    /**
     * 移除定时刷新缓存的任务
     * @param cacheManager
     */
    public void removeTask(CacheManager cacheManager) {
        ScheduledFuture<?> future = cacheFutureMap.remove(cacheManager.getCacheName().getName());
        if (future != null) {
            future.cancel(true);
            log.info("cache {} refresh task remove success", cacheManager.getCacheName());
        }
    }

}